<template>
  <div class="content-wrap">
    <!-- 物料管理 -->
    <operate-area
      ref="operateArea"
      :btn-text="btnText"
      :search-value.sync="searchVal"
      placeholder-text="列表名称"
      @addUser="handleAdd"
      @deleteUser="handleDel"
      @enableUser="handleEnable"
      @disableUser="handleDisable"
      @queryData="getTableList"
    ></operate-area>
    <el-table
      v-loading="tLoading"
      :data="tableData"
      :max-height="tableHeight"
      @selection-change="handleSelectionChange"
      @row-click="checkDetail"
    >
      <el-table-column type="selection" width="48"></el-table-column>
      <el-table-column label="#" width="48" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ scope.$index+(pageNo - 1) * pageSize + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否有值" width="96" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <i v-if="scope.row.hasItem === 1" class="iconfont iconicon_have fs13" style="color: #34c38f"></i>
        </template>
      </el-table-column>

      <el-table-column prop="code" label="ID" width="180" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="name" label="列表名称" min-width="120" :show-overflow-tooltip="true"></el-table-column>

      <el-table-column prop="remark" label="描述" min-width="180" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        width="96"
        :filters="[{ text: '启用', value: '1' }, { text: '禁用', value: '0' }]"
        :filter-method="filterTag"
        filter-placement="bottom-end"
      >
        <template slot="header" slot-scope="{ column }">
          <span>{{ column.label }}</span>
          <i class="iconfont iconicon_filtrate fs13"></i>
        </template>
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.status === '1' ? 'success' : 'info'"
            disable-transitions
          >{{ scope.row.status === '1' ? '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :total="total" :page.sync="pageNo" @pagination="getTableList" />

    <!-- 添加 -->
    <drawer
      title="添加列表"
      size="368px"
      :close-on-press-escape="false"
      :before-close="cancelAdd"
      :visible.sync="dialogAdd"
      direction="rtl"
      class="add-user-drawer"
      custom-class="demo-drawer"
    >
      <div class="demo-drawer__content">
        <list-info ref="addMateriel" :from="formAdd"></list-info>
        <div class="drawer-footer-btn-wrap">
          <footer-btn ref="addFooter" @cancel="cancelAdd" @submitSave="saveAdd"></footer-btn>
        </div>
      </div>
    </drawer>

    <!-- 详情 -->
    <drawer
      size="448px"
      :title="formEdit.name"
      :close-on-press-escape="false"
      :before-close="cancelEdit"
      :visible.sync="dialogEdit"
      direction="rtl"
      custom-class="demo-drawer"
    >
      <div class="demo-drawer__content">
        <el-tabs
          class="user-detail-tabs-wrap"
          tab-position="left"
          type="border-card"
          :value="tabName"
          @tab-click="tabChange"
        >
          <!-- 编辑/详情 -->
          <el-tab-pane name="edit">
            <span slot="label">
              <i class="iconfont iconicon_detail"></i>
            </span>
            <div class="detail-title flex-space-between">
              <p class="title fs16">详细信息</p>
              <el-button v-if="isEdit" type="primary" round @click="handleEdit">
                <i class="iconfont iconicon_edit"></i>
                编辑
              </el-button>
            </div>
            <list-info
              ref="editMateriel"
              :class="isEdit ? '' : 'editshow'"
              :from="formEdit"
              :is-edit="isEdit"
            ></list-info>
            <div class="drawer-footer-btn-wrap" :class="isEdit ? '' : 'footerbtnshow'">
              <footer-btn ref="editFooter" @cancel="isEdit = true" @submitSave="saveEdit"></footer-btn>
            </div>
          </el-tab-pane>

          <!-- 列表值 -->
          <el-tab-pane name="listVal">
            <span slot="label">
              <i class="iconfont iconicon_list"></i>
            </span>

            <div class="detail-title flex-space-between">
              <p class="title fs16">列表值</p>
              <el-radio-group v-model="radioGroupVal" @change="radioGroupChange">
                <el-tooltip
                  v-for="(item, k) in radioGroupList"
                  :key="k"
                  :content="item.tooltipContent"
                  placement="top"
                >
                  <el-radio-button
                    :label="item.value"
                    :disabled="['03', '04', '05'].includes(item.value) && checkedNum === 0"
                  >
                    <i class="iconfont" :class="item.icon"></i>
                  </el-radio-button>
                </el-tooltip>
              </el-radio-group>
            </div>

            <div class="user-info-wrap">
              <el-table
                v-loading="lvLoading"
                :data="lvTableData"
                @selection-change="lvHandleSelectionChange"
              >
                <el-table-column type="selection" width="42"></el-table-column>
                <el-table-column label="#" width="36" :show-overflow-tooltip="true">
                  <template slot-scope="scope">
                    <span>{{ scope.$index + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="name" label="名称" min-width="60" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column
                  prop="code"
                  label="Unicode"
                  width="84"
                  :show-overflow-tooltip="true"
                ></el-table-column>
                <el-table-column prop="status" label="状态" width="60">
                  <template scope="scope">
                    <template>{{ status[scope.row.status] }}</template>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="60">
                  <template scope="scope">
                    <el-tooltip content="编辑" placement="top">
                      <i class="iconfont iconicon_edit" @click="handleLvEdit(scope)"></i>
                    </el-tooltip>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>

          <!-- 使用位置 -->
          <el-tab-pane name="useLocation">
            <span slot="label">
              <i class="iconfont iconicon_location"></i>
            </span>

            <div class="detail-title flex-space-between">
              <p class="title fs16">使用位置</p>
            </div>

            <div class="user-info-wrap">
              <el-table :data="ulTableData">
                <el-table-column prop="name" label="使用属性" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column label="使用分类" :show-overflow-tooltip="true">
                  <template scope="scope">
                    <template>{{ attributeType[scope.row.attributeType] }}</template>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>

          <!-- 操作记录 -->
          <el-tab-pane name="operationRecords">
            <span slot="label">
              <i class="iconfont iconicon_history"></i>
            </span>

            <div class="detail-title flex-space-between">
              <p class="title fs16">操作记录</p>
            </div>
            <div class="user-info-wrap">

              <el-table v-loading="orLoading" :data="orTableData">
                <el-table-column prop label="操作动作" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop label="描述" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop label="操作用户" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop label="操作时间" :show-overflow-tooltip="true"></el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </drawer>

    <Dialog
      ref="lyDelDialog"
      title="提示"
      width="500px"
      top="30vh"
      :btn-text="{submit: '确 认'}"
      @submitSave="handleLvDel"
      @cancel="radioGroupVal = ''"
    >
      <span class="del-content">
        <i class="iconfont iconar-alert"></i>
        <span>此操作将删除该数据，是否继续？</span>
      </span>
    </Dialog>

    <!-- 添加列表值 -->
    <Dialog
      ref="lyDialog"
      :title="lyDialogTitle"
      :btn-auth="{continueAdd: isContinueAddBtn}"
      width="420px"
      @submitSave="lvAddSubmitSave"
      @cancel="lvCancel"
      @continueAdd="lvContinueAdd"
    >
      <template>
        <el-form ref="lvform" label-width="80px" label-position="left" :rules="ruleLvform" :model="lvform">
          <el-form-item label="名称" prop="name">
            <el-input v-model="lvform.name" maxlength="20"></el-input>
          </el-form-item>
          <el-form-item label="Unicode" prop="code">
            <el-input
              v-model="lvform.code"
              @keyup.native="lvform.code = lvform.code.replace(/[^a-zA-Z0-9]/g,'')"
            ></el-input>
          </el-form-item>
          <el-form-item label="状态" style="margin: 0;">
            <el-select v-model="lvform.status">
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
    </Dialog>

    <!-- 添加列表值 -->
    <Dialog
      ref="lyBatchAddDialog"
      title="批量添加列表值"
      width="420px"
      @submitSave="lvBatchAddSubmitSave"
      @cancel="radioGroupVal=''"
    >
      <template>
        <p>
          请输入列表值，每一行是视为一项。
          <br />(每行的填写格式为：列表值|Unicode|描述，其中列表值和Unicode为必填项且系统唯一)<!-- eslint-disable-line -->
        </p>
        <el-input
          v-model="lvBatchVal"
          type="textarea"
          :autosize="{ minRows: 5}"
          placeholder="例如：PCS|01|描述物料的单位"
        ></el-input>
      </template>
    </Dialog>
  </div>
</template>
<script>
import OperateArea from '@/components/OperateArea/index'
import Pagination from '@/components/Pagination/index'
import Drawer from '@/components/Drawer/index'
import ListInfo from './listInfo'
import Dialog from '@/components/Dialog'
import FooterBtn from '@/components/CancelAndSubmitBtnGroup'
import autoTableHeight from '@/utils/autoTableHeight.js'

import {
  postQueryPageList,
  postAdd,
  deleteDels,
  putUpdateEnable,
  putUpdateDisableEnable,
  getView,
  putUpdate,
  getViewtable,
  postAddtable,
  postAdds,
  deleteDelstable,
  putUpdateEnabletable,
  putUpdateDisableEnabletable,
  putUpdatetable,
  getViewDictItem
} from '@/api/adminPage/baseConfig/listValue'

export default {
  name: 'ListValue',
  components: {
    OperateArea,
    Pagination,
    Drawer,
    ListInfo,
    Dialog,
    FooterBtn
  },
  data() {
    return {
      tableHeight: autoTableHeight(270),
      lyDialogTitle: '添加列表值',
      radioGroupVal: '',
      searchVal: '',
      tabName: 'edit',
      btnText: {
        add: '添加',
        del: '删除'
      },
      formAdd: {
        name: '', // 名称
        remark: '', // 描述
        status: '1' // 状态
      },
      numberType: {
        '1': '数值',
        '2': '文本',
        '3': '列表',
        '4': '日期'
      },
      status: {
        '0': '禁用',
        '1': '启用'
      },
      attributeType: {
        '1': '公共属性',
        '2': '专有属性',
        '3': 'BOM',
        '4': '变更记录',
        '5': '关系',
        '6': '附件',
        '7': '使用位置',
        '8': '历史记录',
        '9': '受影响物件',
        '10': '工作流'
      },
      flowsStatus: {
        '0': '否',
        '1': '是'
      },
      formEdit: {},
      lvform: {
        name: '', // 名称
        code: '', // Unicode
        status: '1' // 状态
      },
      lvBatchVal: '',
      selectedData: {},
      tableData: [],
      lvTableData: [],
      orTableData: [],
      ulTableData: [],
      multipleSelection: [],
      lvMultipleSelection: [],
      radioGroupList: [
        {
          tooltipContent: '添加',
          value: '01',
          icon: 'iconicon_add'
        },
        {
          tooltipContent: '批量添加',
          value: '02',
          icon: 'iconpiliangtianjia'
        },
        {
          tooltipContent: '删除',
          value: '03',
          icon: 'iconicon_trash'
        },
        {
          tooltipContent: '启用',
          value: '04',
          icon: 'iconicon_enabled'
        },
        {
          tooltipContent: '禁用',
          value: '05',
          icon: 'iconicon_disabled'
        }
      ],
      ruleLvform: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入Unicode', trigger: 'blur' }]
      },
      tLoading: false,
      lvLoading: false,
      orLoading: false,
      dialogAdd: false,
      dialogEdit: false,
      lvVisible: false,
      isEdit: false,
      isLvEdit: false,
      isContinueAddBtn: false,
      pageNo: 1,
      pageSize: 10,
      total: 0
    }
  },
  computed: {
    checkedNum() {
      return this.lvMultipleSelection.length
    }
  },
  created() {
    this.getTableList()
  },
  mounted() {
    window.onresize = () => {
      this.tableHeight = autoTableHeight(270)
    }
  },
  methods: {
    getTableList(value = false) {
      if (value && typeof value === 'object') {
        this.pageNo = value.page
        this.pageSize = value.limit
      }
      const params = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        name: this.searchVal
      }
      this.tLoading = true
      postQueryPageList(params)
        .then(res => {
          this.tLoading = false
          const records = res.result.records
          this.tableData = records
          this.total = res.result.total
          if (records !== null) {
            records.forEach((item, index) => {
              item.coderuleName = item.baseCoderule
                ? item.baseCoderule.name
                : ''
            })
          }
          this.tableData = records || []
          console.log(this.tableData)
        })
        .catch(() => {
          this.tLoading = false
          this.tableData = []
          this.total = 0
        })
    },
    tabChange(params) {
      this.tabName = params.name
      switch (params.name) {
        case 'listVal':
          this.radioGroupVal = ''
          this.getLVTableList()
          break
        case 'useLocation':
          // 点击主表数据就已经获取了
          break
        case 'operationRecords':
          this.getORTableList()
          break
      }
    },
    // 右侧，列表值表格数据 /使用位置 也是同一个
    getLVTableList() {
      this.lvLoading = true
      getViewtable(this.selectedData.id)
        .then(res => {
          this.lvLoading = false
          this.lvTableData = res
        })
        .catch(() => {
          this.lvTableData = []
          this.lvLoading = false
        })
    },
    // 右侧，操作记录的表格数据
    getORTableList() {},
    radioGroupChange(val) {
      switch (val) {
        case '01':
          this.handelLvAdd()
          break
        case '02':
          this.handelLvBatchAdd()
          break
        case '03':
          this.$refs.lyDelDialog.dialogVisible = true
          break
        case '04':
          this.handleLvEnable()
          break
        case '05':
          this.handleLvDisable()
          break
      }
    },
    // 列表值添加
    handelLvAdd() {
      this.lvform = {
        name: '', // 名称
        code: '', // Unicode
        status: '1' // 状态
      }
      this.isLvEdit = false
      this.isContinueAddBtn = true
      this.lyDialogTitle = '添加列表值'
      this.$refs.lyDialog.dialogVisible = true
    },
    // 列表值批量添加
    handelLvBatchAdd() {
      this.lvBatchVal = ''
      this.$refs.lyBatchAddDialog.dialogVisible = true
    },
    // 列表值删除
    handleLvDel() {
      const ids = this.lvMultipleSelection.map(item => item.id)
      deleteDelstable(ids).then(res => {
        this.handelLVSuccess('删除成功')
        this.$refs.lyDelDialog.dialogVisible = false
        this.getTableList()
      })
    },
    // 列表值启用
    handleLvEnable() {
      const ids = this.lvMultipleSelection.map(item => item.id)
      putUpdateEnabletable(ids).then(res => {
        this.handelLVSuccess('启用成功')
      })
    },
    // 列表值禁用
    handleLvDisable() {
      const ids = this.lvMultipleSelection.map(item => item.id)
      putUpdateDisableEnabletable(ids).then(res => {
        this.handelLVSuccess('禁用成功')
      })
    },
    lvCancel() {
      this.radioGroupVal = ''
      this.$nextTick(() => {
        this.$refs.lvform.resetFields()
      })
    },
    // 列表值继续添加
    lvContinueAdd() {
      this.lvAddSubmitSave(true)
    },
    lvAddSubmitSave(isShow = false) {
      this.$refs.lvform.validate(valid => {
        if (valid) {
          if (this.isLvEdit) {
            putUpdatetable(this.lvform).then(res => {
              this.handelLVSuccess()
              this.$refs.lyDialog.dialogVisible = false
            })
          } else {
            postAddtable({ dictId: this.selectedData.id, ...this.lvform }).then(
              res => {
                this.$refs.lyDialog.dialogVisible = isShow
                this.handelLVSuccess()
                this.getTableList()
                if (isShow) {
                  this.$nextTick(() => {
                    this.radioGroupVal = '01'
                    this.handelLvAdd()
                  })
                }
              }
            )
          }
        }
      })
    },
    lvBatchAddSubmitSave() {
      const valArr = this.lvBatchVal.split(/\n/)
      const params = {
        id: this.selectedData.id,
        text: valArr
      }
      postAdds(params).then(res => {
        this.$refs.lyBatchAddDialog.dialogVisible = false
        this.handelLVSuccess()
        this.getTableList()
      })
    },
    handelLVSuccess(message = '保存成功') {
      this.$message({
        message: message,
        type: 'success'
      })
      this.radioGroupVal = ''
      this.getLVTableList()
    },
    handleLvEdit(scope) {
      this.isLvEdit = true
      getViewDictItem(scope.row.id).then(res => {
        this.lvform = res.result
        this.isContinueAddBtn = false
        this.lyDialogTitle = '编辑列表值'
        this.$refs.lyDialog.dialogVisible = true
      })
    },
    handleAdd() {
      this.formAdd = {
        name: '', // 名称
        remark: '', // 描述
        status: '1' // 状态
      }
      this.isEdit = false
      this.dialogAdd = true
    },
    handleSelectionChange(val) {
      if (val.length) {
        this.$refs.operateArea.$children[1].selectIndex = 1
      } else {
        this.$refs.operateArea.$children[1].selectIndex = -1
      }
      this.multipleSelection = val
    },
    lvHandleSelectionChange(val) {
      this.lvMultipleSelection = val
    },
    getOperateIds() {
      const ids = []
      this.multipleSelection.forEach((item, index) => {
        ids.push(item.id)
      })
      return ids
    },
    handleDel() {
      const ids = this.getOperateIds()
      deleteDels(ids).then(res => {
        this.handelSuccess('删除成功')
      })
    },
    handleEnable() {
      const ids = this.getOperateIds()
      putUpdateEnable(ids).then(res => {
        this.handelSuccess('启用成功')
      })
    },
    handleDisable() {
      const ids = this.getOperateIds()
      putUpdateDisableEnable(ids).then(res => {
        this.handelSuccess('禁用成功')
      })
    },
    handelSuccess(message = '保存成功') {
      this.$message({
        message: message,
        type: 'success'
      })
      this.getTableList()
    },

    checkDetail(item) {
      this.selectedData = item
      this.tabName = 'edit'
      getView(item.id).then(res => {
        this.formEdit = res.result
        this.formEdit.id = item.id
        this.isEdit = true
        this.dialogEdit = true
        if (res.result && res.result.baseAttribute !== null) {
          this.ulTableData = res.result.baseAttribute
        } else {
          this.ulTableData = []
        }
      })
    },
    filterTag(value, row, column) {
      const property = column['property']
      return row[property] === value
    },
    cancelAdd() {
      this.$refs.addMateriel.$refs.addDrawer.resetFields()
      this.dialogAdd = false
    },
    cancelEdit() {
      this.$refs.editMateriel.$refs.addDrawer.resetFields()
      this.dialogEdit = false
    },
    saveAdd() {
      this.$refs.addMateriel.$refs.addDrawer.validate(valid => {
        if (valid) {
          this.$refs.addFooter.loading = true
          // 新增
          postAdd(this.formAdd)
            .then(res => {
              this.$refs.addFooter.loading = false
              this.dialogAdd = false
              this.selectedData = res.result
              this.handelSuccess()
              // 打开列表值添加弹框
              this.handelLvAdd()
            })
            .catch(() => {
              this.$refs.addFooter.loading = false
            })
        }
      })
    },
    saveEdit() {
      this.$refs.editMateriel.$refs.addDrawer.validate(valid => {
        if (valid) {
          this.$refs.editFooter.loading = true
          putUpdate(this.formEdit)
            .then(res => {
              this.$refs.editFooter.loading = false
              this.isEdit = true
              this.handelSuccess()
            })
            .catch(() => {
              this.$refs.editFooter.loading = false
            })
        }
      })
    },
    handleEdit() {
      this.isEdit = false
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/assets/styles/variables.scss";
@import "@/assets/styles/user-drawer.scss";

::v-deep .el-table tbody tr:hover > td {
  cursor: pointer;
}
::v-deep .el-textarea__inner {
  resize: none;
}
::v-deep .user-detail-tabs-wrap {
  height: calc(100vh - 67px);
  border: none;
  .detail-title {
    margin-bottom: 25px;
    color: $fontColor;
  }
  .el-tabs__header {
    margin-right: 0;
    background: $background;
  }
  .el-tabs__item {
    padding: 0 13px;
    height: 59px;
    line-height: 59px;
  }
  .el-tabs__content {
    padding: 16px;
  }
  .el-radio-group {
    label {
      margin: 0;
    }
    .el-radio-button {
      border: none;
      &:first-child .el-radio-button__inner {
        border-radius: 16px 0 0 16px;
      }
      &:last-child .el-radio-button__inner {
        border-radius: 0 16px 16px 0;
      }
      .el-radio-button__inner {
        background-color: #74788d;
        color: #ffffff;
        border: none;
        padding: 10px 16px;
        .iconfont {
          font-size: 12px;
        }
        @media (max-width: 1360px) {
          .iconfont {
            font-size: 12px !important;
          }
        }
      }
      .el-radio-button__inner:hover {
        color: #fff;
        background-color: #556EE6;
        border-color: #556EE6;
        box-shadow: -1px 0 0 0 #556EE6;
      }
      .el-radio-button__orig-radio:checked+.el-radio-button__inner {
        color: #fff;
        background-color: #556ee6;
        border-color: #556ee6;
        box-shadow: -1px 0 0 0 #556ee6;
      }
    }
  }
}
::v-deep .user-detail-tabs-wrap .el-radio-group .el-radio-button.is-disabled .el-radio-button__inner:hover {
  background-color: #74788D;
  color: #FFFFFF;
  border: none;
  box-shadow: -1px 0 0 0 #74788D;
}
.del-content {
  .iconar-alert {
    color: #f1b44c;
    font-size: 20px;
    line-height: 20px;
    vertical-align: middle;
    padding-right: 12px;
  }
  span {
    line-height: 20px;
    font-size: 14px;
  }
}
.drawer-footer-btn-wrap {
  position: absolute;
  bottom: 20px;
  right: 0;
  left: 0;
  padding: 16px 16px 20px;
  background: $white;
  border-top: 1px solid $borderColor;
  text-align: right;
}
</style>
